import Taro from '@tarojs/taro';
import u from 'updeep'
import request from '../util/request'

const INITDATA = {
  listData: [], // 列表数据
  limit: 10,
  offset: 0,
  total: 0, // 总数
  typeId: 0,
  showDrawer:false,
  choseType: [
    {id: 0, name: '全部'},
    {id: '机械制造', name: '机械制造'},
    {id: '互联网IT', name: '互联网IT'}
  ]
}
export default {
  namespace: 'companyList',
  state: {...INITDATA},
  reducers: {
    updateState(state, {payload}) {
      return u({
        ...payload
      }, state)
    },
    initData(state, action) {
      return {
        ...state,
        ...action.payload,
        ...INITDATA
      }
    }
  },
  effects: {

    * loadType({payload = {}}, {put, call}) {
      const {data} = yield call(request, {
        url: SERVERURL + '/service/type/types',
        method: 'post',
        data:{
          category:"business"
        }
      })
      if (data && data.data instanceof Array) {
        const d = data.data || {};

        let choseType = [{id: 0, name: '全部'}]
        for (let index in d){
          choseType.push({id:d[index].id,name:d[index].typeName})
        }

        yield put({
          type: 'updateState',
          payload: {
            choseType: choseType
          }
        })
      } else {
        Taro.showToast({
          title: (data || {}).msg || '获取列表数据失败',
          icon: 'none'
        })
      }
    },

    // 获取列表数据
    * loadList({payload = {}}, {select, put, call}) {
      const {
        limit, offset, listData,typeId,
        name
      } = yield select(({companyList}) => companyList)
      let page = payload.offset || offset;
      let nameData = payload.name || name;
      const param = {
        limit, name: nameData,
        typeId:typeId,
        offset: page
      }
      const {data} = yield call(request, {
        url: SERVERURL + 'service/business/getPage',
        data: param,
        method: 'POST',
      })

      if (data && data.rows instanceof Array) {

        if (data.rows.length > 0) {
          const d = data.rows || {};
          yield put({
            type: 'updateState',
            payload: {
              listData: listData.concat(d),
              total: data.total
            }
          })
        } else {
          Taro.showToast({
            title: (data || {}).msg || '没有更多数据',
            icon: 'none'
          })
        }


      } else {
        Taro.showToast({
          title: (data || {}).msg || '获取列表数据失败',
          icon: 'none'
        })
      }
    },
  }
};
